package db

import (
	"context"
	"log"
	"os"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"

	"shop-manager/config"
	"shop-manager/internal/do"
)

func New(ctx context.Context) (db *gorm.DB, err error) {
	dsn := config.Get().DB.DSN

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second, // Slow SQL threshold
			LogLevel:                  logger.Info, // Log level
			IgnoreRecordNotFoundError: true,        // Ignore ErrRecordNotFound error for logger
			ParameterizedQueries:      true,        // Don't include params in the SQL log
			Colorful:                  true,        // Disable color
		},
	)

	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		return nil, err
	}

	if config.Get().DB.AutoMigrate {
		if err := db.AutoMigrate(&do.CategoryMeta{}); err != nil {
			return nil, err
		}
		if err := db.AutoMigrate(&do.Category{}); err != nil {
			return nil, err
		}
		if err := db.AutoMigrate(&do.Supermarket{}); err != nil {
			return nil, err
		}
		if err := db.AutoMigrate(&do.SalesPerson{}); err != nil {
			return nil, err
		}
		if err := db.AutoMigrate(&do.Person{}); err != nil {
			return nil, err
		}
		if err := db.AutoMigrate(&do.SupermarketDirector{}); err != nil {
			return nil, err
		}
		if err := db.AutoMigrate(&do.Goods{}); err != nil {
			return nil, err
		}

		// 厂家返点
		if err := db.AutoMigrate(&do.FactoryRebate{}); err != nil {
			return nil, err
		}
		// 合同
		if err := db.AutoMigrate(&do.Contract{}); err != nil {
			return nil, err
		}
	}
	return db, nil
}
